package com.ocm.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author quanvo
 *
 */
public class SetTimezoneOffsetFilter implements Filter {

   public static final String PROPERTY_TIMEZONE_OFFEST = "OCM.timezoneOffset";

   public static final String COOKIE_NAME = "timezoneOffset";

   public void destroy() {
   }

   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
         ServletException {
      HttpServletRequest req = (HttpServletRequest) request;
      HttpServletResponse res = (HttpServletResponse) response;
      if (req.getSession().getAttribute(PROPERTY_TIMEZONE_OFFEST) == null) {
         if (req.getCookies() != null) {
            for (Cookie cookie : req.getCookies()) {
               if (COOKIE_NAME.equals(cookie.getName())) {
                  int timezoneOffsetMinutes = Integer.parseInt(cookie.getValue());
                  req.getSession().setAttribute(PROPERTY_TIMEZONE_OFFEST, timezoneOffsetMinutes);
                  cookie.setMaxAge(0);
                  res.addCookie(cookie);
               }
            }
         }
      }
      chain.doFilter(request, response);
   }

   public void init(FilterConfig config) throws ServletException {
   }

}
